//
//  DSPOAuthViewController.swift
//  SWweibo
//
//  Created by 杜守鹏 on 15/12/29.
//  Copyright © 2015年 杜守鹏. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

var WB_APPKEY = "334873793"
var WB_REGIRECTURI = "http://www.baidu.com/"
var WB_SECRET = "8e3bdea826e737180e1ce2fe81273cb7"

class DSPOAuthViewController: UIViewController,UIWebViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(webView)
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REGIRECTURI)")!
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {

        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request)
        guard let  urlSting = request.URL?.absoluteString else{
            return true
        }
    
        if  !urlSting.hasPrefix(WB_REGIRECTURI){
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code="){
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            DSPDSPUserCountViewModel.sharedUserCountViewModel.acessTokenFromCode(code, completed: { (isSucceed) -> () in
                
                                  SVProgressHUD.dismiss()
                    let vc = DSPWelcomeController()
                    self.presentViewController(vc, animated: true , completion: nil)
           

            })
        }

        return false
    }
    
    
    lazy var webView:UIWebView = {
        let webView = UIWebView()
        webView.frame = UIScreen.mainScreen().bounds
        webView.delegate = self
        return webView
    }()
    
    deinit{
    print("oauth bye")
    }
}
